//
//  PublishTopicViewController.m
//  yigou
//
//  Created by wangdianlei on 2017/1/17.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "PublishTopicViewController.h"
#import "PlaceholderTextView.h"
#import "PublishTopicImageCell.h"
#import "MyAddTribeListViewController.h"
#import "ELCImagePickerController.h"
#import "QBImagePicker/QBImagePickerController.h"
#import "GCQiniuUploadManager.h"
#import "IQKeyboardManager.h"

@interface PublishTopicViewController () <UINavigationControllerDelegate, UIImagePickerControllerDelegate, ELCImagePickerControllerDelegate, QBImagePickerControllerDelegate, UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, PublishTopicDeleteDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) PlaceholderTextView* contentTextView;
@property (strong, nonatomic) UILabel *tribename;
@property (strong, nonatomic) NSMutableArray *imgArray;
@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;
@property (assign, nonatomic) CGFloat itemWidth;


@property (strong, nonatomic) NSString *docid;

@end

@implementation PublishTopicViewController {
    UICollectionView *mcollectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.contentTextView = [[PlaceholderTextView alloc]initWithFrame:CGRectMake(12, 10, ScreenWidth-24, 114)];
    self.contentTextView.delegate = self;
    self.contentTextView.font = [UIFont systemFontOfSize:16.f];
    self.contentTextView.textColor = [UIColor blackColor];
    self.contentTextView.textAlignment = NSTextAlignmentLeft;
    self.contentTextView.editable = YES;
    self.contentTextView.placeholderColor = [UIColor lightGrayColor];
    self.contentTextView.placeholder = @"输入这一刻你想说的话，给懂的人听";
    [self.view addSubview:self.contentTextView];
    
//    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 12 + 114, ScreenWidth, 1)];
//    line.backgroundColor = LineColor;
//    [self.view addSubview:line];
    
    //照片Collection
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    //    flowlayout.minimumInteritemSpacing = 5;
    //    flowlayout.minimumLineSpacing = 5;
    //    flowlayout.itemSize = CGSizeMake((kScreenWidth-24-15)/4, 52);
    self.itemWidth = (ScreenWidth - 24 - 24 * 3) / 4;
    flowlayout.itemSize = CGSizeMake(self.itemWidth, self.itemWidth);
    // 设置最小行间距
    flowlayout.minimumLineSpacing = 19;
    // 设置垂直间距
    flowlayout.minimumInteritemSpacing = 24;
    
    mcollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12, 114 + 12, ScreenWidth-24, self.itemWidth + 19) collectionViewLayout:flowlayout];
    [self.view addSubview:mcollectionView];
    mcollectionView.backgroundColor = [UIColor whiteColor];
    
    [mcollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.height.mas_equalTo(self.itemWidth + 19);
        make.top.equalTo(self.contentTextView.mas_bottom).offset(12);
    }];
    [mcollectionView registerClass:[PublishTopicImageCell class] forCellWithReuseIdentifier:@"PublishTopicImageCell"];
    mcollectionView.delegate = self;
    mcollectionView.dataSource = self;
    [mcollectionView reloadData];
    [self addChooseTribe];
    
    [PublishData sharedPublishData].chooseTribeID = @"";
    [PublishData sharedPublishData].chooseTribeName = @"";
}

- (void)addChooseTribe {
    UIView *bg = [[UIView alloc] init];
    [self.view addSubview:bg];
    [bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(50);
        make.top.equalTo(mcollectionView.mas_bottom).offset(0);
    }];

    bg.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickChooseTribe)];
    tap.numberOfTapsRequired = 1;
    [bg addGestureRecognizer:tap];
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
    line1.backgroundColor = LineColor;
    [bg addSubview:line1];
    
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(12, 1, 100, 48)];
    title.text = @"选择部落";
    title.font = [FontTool fontWithSize:15];
    title.textColor = [UIColor blackColor];
    title.textAlignment = NSTextAlignmentLeft;
    [bg addSubview:title];
    
    self.tribename = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 30 - 18 - 5 - 100, 1, 100, 48)];
    self.tribename.text = @"";
    self.tribename.font = [FontTool fontWithSize:15];
    self.tribename.textColor = [UIColor blackColor];
    self.tribename.textAlignment = NSTextAlignmentRight;
    [bg addSubview:self.tribename];
    
    UIImageView *arrow = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth - 30, 16, 18, 18)];
    arrow.image = [UIImage imageNamed:@"rightarrow"];
    [bg addSubview:arrow];
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(0, 49, ScreenWidth, 1)];
    line2.backgroundColor = LineColor;
    [bg addSubview:line2];
}

- (void)clickChooseTribe {
    [self.view endEditing:YES];
    MyAddTribeListViewController *vc = [[MyAddTribeListViewController alloc] initWithNibName:@"MyAddTribeListViewController" bundle:nil];
    vc.type = IMyAddTribeListChoose;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"发布帖子"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *button = [ViewFactory makeNavigationTextButtonWhite:@"发布"];
    [button addTarget:self action:@selector(goPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    if ([PublishData sharedPublishData].chooseTribeName) {
        self.tribename.text = [PublishData sharedPublishData].chooseTribeName;
    }
    [IQKeyboardManager sharedManager].enable = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
}

- (void)goPop {
    [self.view endEditing:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要取消发布帖子吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //确定
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSString*)DataTOjsonString:(id)object {
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (void)goPublish {
    [self.view endEditing:YES];
    if (self.contentTextView.text.length == 0) {
        [ViewFactory showInfoMsg:@"请输入内容！"];
        return;
    }
    
    if (self.contentTextView.text.length > 144) {
        [ViewFactory showInfoMsg:@"内容超长！"];
        return;
    }
    
    if ([[PublishData sharedPublishData].chooseTribeID isEqualToString:@""]) {
        [ViewFactory showInfoMsg:@"请选择部落！"];
        return;
    }
    
    if (self.imgArray.count > 0 && self.imgArray.count <= 5) {
        [ViewFactory showLoading];
        [self uploadImages];
    } else if (self.imgArray.count > 5) {
        [ViewFactory showInfoMsg:@"最多选择5张图片!"];
        return;
    } else {
        [ViewFactory showInfoMsg:@"请至少选择一张图片!"];
        return;
    }
}

- (void)uploadImages {
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    for (NSInteger i = 0; i < self.imgArray.count; i++) {
        UIImage *img = self.imgArray[i];
        NSData *imgdata = UIImageJPEGRepresentation(img, 1.0);
        [dataarray addObject:imgdata];
    }
    
    [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
        
    } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            [self.imgurlArray addObject:resurl];
            [self.imgidArray addObject:link];
        }
    } allTasksCompletion:^{
        [self uploadDoc];
    }];
}

- (void)uploadDoc {
    NSString *coverid = @"";
    if (self.imgidArray.count > 0) {
        coverid = self.imgidArray[0];
    }
    
    NSMutableArray *parray = [[NSMutableArray alloc] init];
    NSDictionary *pdict = @{
                            @"sort_index": @0,
                            @"md": self.contentTextView.text
                            };
    [parray addObject:pdict];
    
    NSMutableArray *picarray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
        NSString *imgid = self.imgidArray[i];
        NSString *imgidurl = self.imgurlArray[i];
        NSDictionary *picdict = @{
                                @"sort_index": [NSNumber numberWithInteger:i],
                                @"id": imgidurl,
                                @"media_type": @"00",
                                @"tag": @[
                                        @{
                                            @"sort_index": @1,
                                            @"label_value": @"http://www.baidu.com",
                                            @"txt_orient": @"0",
                                            @"label_x": @"100",
                                            @"label_y": @"100",
                                            @"label_name": @"艺术1"
                                            },
                                        @{
                                            @"sort_index": @2,
                                            @"label_value": @"",
                                            @"txt_orient": @"0",
                                            @"label_x": @"200",
                                            @"label_y": @"200",
                                            @"label_name": @"艺术2"
                                            }
                                        ]
                                };
        [picarray addObject:picdict];
    }
    
    NSDictionary *qndict =
    @{
      @"title": self.contentTextView.text,
      @"desc": self.contentTextView.text,
      @"cover_img": @{
              @"id": coverid,
              @"media_type": @"00",
              @"is_cover": @"00",
              @"tag": @[
                      @{
                          @"sort_index": @1,
                          @"label_value": @"http://www.baidu.com",
                          @"txt_orient": @"0",
                          @"label_x": @"100",
                          @"label_y": @"100",
                          @"label_name": @"艺术1"
                          },
                      @{
                          @"sort_index": @2,
                          @"label_value": @"",
                          @"txt_orient": @"0",
                          @"label_x": @"200",
                          @"label_y": @"200",
                          @"label_name": @"艺术2"
                          }
                      ]
              },
      @"content": @{
              @"paragraph": parray,
              @"img": picarray              }
      };
    
    NSData *qndata =[qndict JSONData];
    [[GCQiniuUploadManager sharedInstance] uploadData:qndata progress:^(float percent) {
        DYLog(@"upload percent:%f", percent);
    } completion:^(NSError *error, NSString *link, NSInteger index) {
        if (link == nil) {
            [ViewFactory showErrorStrMsg:@"上传失败！"];
            return;
        }
        
        DYLog(@"upload link:%@", link);
        NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
        self.docid = resurl;
        [self publishTopic];
    }];
}

- (void)publishTopic {
    //content_type：00话题 01文章 is_cover:00封面图 01非封面图 media_type:00
    NSString *coverurl = @"";
    if (self.imgurlArray.count > 0) {
        coverurl = self.imgurlArray[0];
    }
    NSMutableArray *picarray = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
        NSString *iscover = @"01";
        if (i == 0) {
            iscover = @"00";
        }
        NSString *imgid = self.imgidArray[i];
        NSString *imgurl = self.imgurlArray[i];
        NSDictionary *picdict = @{
                                  @"is_cover": iscover,
                                  @"media_id": imgurl,
                                  @"media_size": @0,
                                  @"media_type": @"00",
                                  @"media_url": imgurl,
                                  @"sortindex": [NSNumber numberWithInteger:i],
                                  @"tag": @[
                                          @{
                                              @"label_type": @"string",
                                              @"label_value": @"string",
                                              @"label_x": @"string",
                                              @"label_y": @"string",
                                              @"sortindex": @0,
                                              @"txt_orient": @"string"
                                              }
                                          ]
                                  };
        [picarray addObject:picdict];
    }
    
    NSString *tribeid = @"0";
    if ([PublishData sharedPublishData].chooseTribeID.length > 0) {
        tribeid = [PublishData sharedPublishData].chooseTribeID;
    }
    NSDictionary *textdict = @{
                               @"content_id": @0,
                               @"content_type": @"00",
                               @"coverImg": coverurl,
                               @"desc": self.contentTextView.text,
                               @"doc_id": self.docid,
                               @"media": picarray,
                               @"title": self.contentTextView.text,
                               @"tribe_id": tribeid,
                               @"user_id": [UserData userid]
                               };
    
    NSString *urlStr = [NSString stringWithFormat:@"%@/hyContent/saveContent",APIYIGOU];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    [manager POST:urlStr parameters:textdict success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100) {
            [ViewFactory showSuccess:@"发布成功！"];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [ViewFactory showErrorStrMsg:@"发布失败！"];
        }
        DYLog(@"result:%@", dict.description);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
        [ViewFactory showErrorStrMsg:@"发布失败！"];
    }];
}

- (void)textViewDidChange:(UITextView *)textView {
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (self.imgArray.count + 1);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    PublishTopicImageCell *cell = (PublishTopicImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"PublishTopicImageCell" forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.delegate = self;
    if (self.imgArray.count > 0) {
        if (indexPath.row == self.imgArray.count) {
            cell.deletebtn.hidden = YES;
            cell.icon.image = [UIImage imageNamed:@"post_Camera"];
        } else {
            cell.deletebtn.hidden = NO;
            UIImage *img = self.imgArray[indexPath.row];
            cell.icon.image = img;
        }
    } else {
        cell.deletebtn.hidden = YES;
        cell.icon.image = [UIImage imageNamed:@"post_Camera"];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    if (self.imgArray.count == 0) {
        [self clickAdd];
    } else {
        if (indexPath.row == self.imgArray.count) {
            [self clickAdd];
        }
    }
}

- (void)publishTopicDeleteOne:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.row;
    [self.imgArray removeObjectAtIndex:index];
    NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
    [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo((self.itemWidth + 19) * count);
    }];
    [mcollectionView reloadData];
}

- (void)clickAdd {
    if (self.imgArray.count >= 5) {
        [ViewFactory showInfoMsg:@"最多选择5张图片！"];
        return;
    }
    [self.view endEditing:YES];
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    [self presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 5 - self.imgArray.count;
    if (ISIOS7 || ISIOS8_0) {
        ELCImagePickerController *elcPicker = [ELCImagePickerController new];
        elcPicker.maximumImagesCount = maxCount;
        elcPicker.imagePickerDelegate = self;
        [self presentViewController:elcPicker animated:YES completion:nil];
    } else {
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.assetCollectionSubtypes =@[
                                                         @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                         @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                         @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                        @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                         @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                         ];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        imagePickerController.maximumNumberOfSelection = maxCount;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.imgArray insertObject:image atIndex:0];
        NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
    }];
}

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    //TODO:changeToData
    [picker dismissViewControllerAnimated:YES completion:^{
        for (int i = 0;i<[info count];i++) {
            UIImage *img = [[info objectAtIndex:i]objectForKey:@"UIImagePickerControllerOriginalImage"];
            [self.imgArray insertObject:img atIndex:0];
        }
        NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
    }];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        DYLog(@"cancl");
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if(imageData) {
                [self.imgArray insertObject:[UIImage imageWithData:imageData] atIndex:0];
                select++;
            }
            if(select == count) {
                NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
                [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo((self.itemWidth + 19) * count);
                }];
                [mcollectionView reloadData];
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                
                return;
            }
        }];
        
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}

ARRAY_INIT(imgArray)
ARRAY_INIT(imgurlArray)
ARRAY_INIT(imgidArray)

@end
